package org.elec.mac.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by Bean on 2017/5/26.
 */
@Slf4j
public class WebKit {

    /**
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(header);
    }

    /**
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String requestJson(HttpServletRequest request) {
        try {
            ServletInputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            StringBuilder builder = new StringBuilder();
            while (StringUtils.isNotBlank(line = reader.readLine())) {
                builder.append(line);
            }
            log.info(builder.toString());
            return builder.toString();
        }
        catch (Exception ex) {
            log.error("RequestJson类型转换错误", ex);
        }
        return null;
    }
}
